import webapp2
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import json

class ArduinoInfo(db.Model):
    """Models a data report from an arduino"""
    token = db.IntegerProperty()
    temperature = db.IntegerProperty()
    proximity = db.IntegerProperty()
    ambient = db.IntegerProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    
class Token(db.Model):
    """Models a data report from an arduino"""
    value = db.IntegerProperty()
    date = db.DateTimeProperty(auto_now_add=True)

def guestbook_key(guestbook_name=None):
  """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
  return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')
    

class MainPage(webapp2.RequestHandler):
    
    
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        tokens = Token(value = 610526241).put()
        g = ArduinoInfo.gql("")
        results = g.fetch(limit=5)
        for song in results:
            self.response.out.write(song.temperature)

class UsersHandler(webapp2.RequestHandler):  

    def get(self, name):
        self.response.out.write('Hello '+ name+'!') 
        
class DataHandler(webapp2.RequestHandler):  

    def post(self):
        data = json.loads(self.request.body)
        if('token' in data):
            g = Token.gql("WHERE value = :1", data['token'])
            if (g.count() > 0):
                info = ArduinoInfo(token = data['token'], temperature= data['temperature'],proximity = data['proximity'],ambient = data['ambient'])
                info.put();
            else:
                self.error(403) # access denied
                return
        else:
            self.error(403) # access denied
            return
            

        
        
        
        


application = webapp2.WSGIApplication([('/', MainPage),(r'/users/(.*)',UsersHandler),(r'/rest',DataHandler)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
